package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"

	"blog/routers"
	"blog/service/consul"
	"blog/service/model"
	"blog/util/setting"
	"os"
	"os/signal"
	"syscall"
)

func init() {
	setting.InitSetting()
	model.InitDB()
	model.InitRedis()
}

// @title Golang Gin API
// @version 1.0
// @description An example of gin
// @termsOfService https://blog
// @license.name MIT
// @license.url https://blog/blob/master/LICENSE
func main() {
	gin.SetMode(setting.RunMode)

	routersInit := routers.InitRouter()
	readTimeout := setting.ReadTimeout
	writeTimeout := setting.WriteTimeout
	endPoint := fmt.Sprintf(":%d", setting.HTTPPort)
	maxHeaderBytes := 1 << 20

	server := &http.Server{
		Addr:           endPoint,
		Handler:        routersInit,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}

	errChan := make(chan error)
    go func(server *http.Server) {
		consul.RegService("blog_service","consul/health/tags") //调用注册服务程序
		log.Printf("[info] start http server listening %s", endPoint)
        err := server.ListenAndServe()
        if err != nil {
            log.Println(err)
            errChan <- err
        }
    }(server)
    go func() {
        sigChan := make(chan os.Signal)
        signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
        errChan <- fmt.Errorf("%s", <-sigChan)
    }()
    getErr := <-errChan //只要报错 或者service关闭阻塞在这里的会进行下去
    consul.UnRegService("blog_service")
	log.Println(getErr)

	//server.ListenAndServe()

	// If you want Graceful Restart, you need a Unix system and download github.com/fvbock/endless
	//endless.DefaultReadTimeOut = readTimeout
	//endless.DefaultWriteTimeOut = writeTimeout
	//endless.DefaultMaxHeaderBytes = maxHeaderBytes
	//server := endless.NewServer(endPoint, routersInit)
	//server.BeforeBegin = func(add string) {
	//	log.Printf("Actual pid is %d", syscall.Getpid())
	//}
	//
	//err := server.ListenAndServe()
	//if err != nil {
	//	log.Printf("Server err: %v", err)
	//}
}
